package com.peng.edu.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.peng.edu.entity.Subject;
import com.peng.edu.entity.excel.SubjectData;
import com.peng.edu.entity.subject.OneSubject;
import com.peng.edu.entity.subject.TwoSubject;
import com.peng.edu.listener.SubjectExcelListener;
import com.peng.edu.mapper.SubjectMapper;
import com.peng.edu.service.SubjectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author Dengp
 * @since 2022-06-14
 */
@Service
public class SubjectServiceImpl extends ServiceImpl<SubjectMapper, Subject> implements SubjectService {

    //添加课程分类
    @Override
    public void addSubject(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(), SubjectData.class,new SubjectExcelListener(this)).sheet().doRead();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    //课程分类列表（树形）
    @Override
    public List<OneSubject> getAllSubject() {
        List<OneSubject> result = new ArrayList<>();
        LambdaQueryWrapper<Subject> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Subject::getParentId,"0");
        //遍历一级课程
        List<Subject> list = this.list(queryWrapper);
        list.stream().forEach(item->{
            OneSubject oneSubject= this.getTwoSubject(item);
            result.add(oneSubject);
        });
        return result;
    }

    //根据一级id获取二级课程
    private OneSubject getTwoSubject(Subject subject) {
        OneSubject oneSubject = new OneSubject();
        BeanUtils.copyProperties(subject,oneSubject);
        //根据一级课程id查二级课程
        LambdaQueryWrapper<Subject> queryWrapperTwo = new LambdaQueryWrapper<>();
        queryWrapperTwo.eq(Subject::getParentId, subject.getId());
        List<Subject> TwoSubjectList = this.list(queryWrapperTwo);
        ArrayList<TwoSubject> twoSubjectArrayList = new ArrayList<>();
        for (Subject twoSubjects : TwoSubjectList) {
            TwoSubject twoSubject = new TwoSubject();
            BeanUtils.copyProperties(twoSubjects,twoSubject);
            twoSubjectArrayList.add(twoSubject);
        }
        oneSubject.setChildren(twoSubjectArrayList);
        return oneSubject;
    }
}
